#include <iostream>
#include <unistd.h>
#include <cstdlib>
#include <string>

using namespace std;

bool GetQuery(std::string& query)
{
    //cerr << "now in CGI" <<  endl;

    string method =  getenv("METHOD");
    if("GET" == method)
    {
        cerr << "CGI GET::" << endl;

        query = getenv("QUERY");
        
    }
    else if("POST" == method)
    {
        cerr << "CGI POST::" << endl;

        size_t contentLens = atoi(getenv("CONTENT_LENGTH"));
        char ch = 0;

        while(contentLens--)
        {
            read(0, &ch, 1);
            query.push_back(ch);
        }
        
    }
    else
    {
        //...
        return false;
    }

    cerr << "CGI QUERY:" << query << endl;
    return true;
}

bool Cut1Query(std::string &inBuf, const std::string& sep, std::string &outBuf1, std::string &outBuf2)
{
    auto pos = inBuf.find(sep);
    if(pos != std::string::npos)
    {
        outBuf1 = inBuf.substr(0, pos);
        outBuf2 = inBuf.substr(pos+sep.size());

        return true;
    }

    return false;
}

int main(){
    std::string query;
    GetQuery(query);

    //数据分析并处理 再返回到服务器
    //处理::  x=1&y=2
    std::string str1;
    std::string str2;
    Cut1Query(query, "&", str1, str2);

    std::string name1;
    std::string value1;
    Cut1Query(str1, "=", name1, value1);

    std::string name2;
    std::string value2;
    Cut1Query(str2, "=", name2, value2);

    //cout 会显示到服务器端原父进程
    std::cout << "CGIdata: " << name1 <<" : " << value1 << std::endl;
    std::cout << "CGIdata: " << name2 <<" : " << value2 << std::endl;

    return 0;
}